package com.mcp.converter.domain.rule.compatibility.function;

import com.mcp.converter.domain.checker.IncompatibilityDetail;
import com.mcp.converter.shared.response.sql.SQLElement;
import com.mcp.converter.domain.rule.compatibility.AbstractFunctionRule;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * NTH_VALUE函数兼容性规则
 * OceanBase中NTH_VALUE函数的实现与Oracle有细微差异
 * @author zengxiong
 */
public class NthValueFunctionRule extends AbstractFunctionRule {

    private static final String RULE_ID = "FN008";
    private static final String RULE_NAME = "NTH_VALUE函数实现差异";
    private static final String RULE_DESCRIPTION = "OceanBase中NTH_VALUE函数的实现与Oracle存在细微差异";

    public NthValueFunctionRule() {
        super(RULE_ID, RULE_NAME, RULE_DESCRIPTION);
        setIncompatibilityDetail(
            "OceanBase中NTH_VALUE函数在以下方面与Oracle存在差异：\n" +
            "1. NULL值的处理方式\n" +
            "2. FROM FIRST/LAST选项的行为\n" +
            "3. 窗口边界的处理\n" +
            "4. RESPECT NULLS/IGNORE NULLS选项的实现",
            "可能导致：\n" +
            "1. 返回值在某些情况下不一致\n" +
            "2. 窗口范围计算结果不同\n" +
            "3. NULL值影响的行为差异",
            "建议：\n" +
            "1. 明确指定FROM FIRST/LAST选项\n" +
            "2. 显式指定RESPECT NULLS/IGNORE NULLS\n" +
            "3. 使用明确的窗口定义（ROWS或RANGE）\n" +
            "4. 对NULL值情况进行充分测试\n" +
            "5. 考虑使用其他窗口函数如LAG/LEAD作为替代",
            IncompatibilityDetail.Severity.MEDIUM
        );
    }

    @Override
    public boolean matches(Object target) {
        if (target instanceof SQLElement) {
            SQLElement element = (SQLElement) target;
            if (isFunctionElement(element)) {
                String functionName = element.getName().toUpperCase();
                return "NTH_VALUE".equals(functionName);
            }
        }
        return false;
    }
    
    @Override
    public Set<String> getIncompatibleFunctions() {
        // NTH_VALUE在OceanBase中是支持的，但存在实现差异，不应标记为完全不兼容
        return new HashSet<>();
    }
}
